package com.qdlc.p2p.dal.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.LogTemplateType;
import com.qdlc.p2p.common.constant.LogTplNid;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.FreemarkerUtil;
import com.qdlc.p2p.common.util.LogFactory;
import com.qdlc.p2p.dal.common.LogTemplateHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dao.AccountLogDao;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.AccountLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AccountLogModel;
import com.qdlc.p2p.dal.mybatis.model.mapper.AccountLogMapper;
import com.qdlc.p2p.dal.mybatis.pager.PageProxyBuilder;
import com.qdlc.p2p.dal.mybatis.pager.core.PageParameter;
import com.qdlc.p2p.dal.util.UserUtils;

@Repository("accountLogDao")
public class AccountLogDaoImpl implements AccountLogDao {

	private static final Logger logger = LogFactory.ACCOUNT_LOGGER;
	
	@Resource
	AccountLogMapper accountLogMapper;
	
	@Override
	public void save(AccountLog accountLog){
		accountLogMapper.insert(accountLog);
	}
	
    @Override
    public PageDataList<AccountLogModel> accountLogList(AccountLogModel model, int pageNumber, int pageSize) {
    	
    	List<AccountLogModel> accountLogModelList;
    	
    	//使用分页代理器
    	PageProxyBuilder<AccountLogMapper> proxy = PageProxyBuilder.newBuilder(AccountLogMapper.class);
    	proxy.setPageParameter(pageNumber, pageSize);
    	String searchName = model.getSearchName();
    	
    	//查询分页数据
    	if(StringUtils.isNotBlank(searchName)){
    		accountLogModelList = proxy.createProxy().findByUserName(searchName);
    	}else{
    		model.setStartDateAndEndDate();
    		accountLogModelList = proxy.createProxy().findByModel(model);
    	}
    	
    	//获取分页参数
    	PageParameter pageParameter = proxy.getPageParameter();
    	
    	//设置派发用户名称
    	setToUserName(accountLogModelList);
    	
    	PageDataList<AccountLogModel> pageDataList = new PageDataList<AccountLogModel>(pageParameter.convert2Page(), accountLogModelList);
    	
    	return pageDataList;
    }
    
    private void setToUserName(List<AccountLogModel> list){
    	if(list == null){
    		return;
    	}
    	
    	for(AccountLogModel accountLogModel: list){
    		long userId = accountLogModel.getUserId();
    		long toUserId = accountLogModel.getToUserId();
    		if(userId == toUserId){
    			//直接使用操作用户名称
    			accountLogModel.setToUserName(accountLogModel.getUserName());
    		}else{
    			if(toUserId <= 0){
    				//表示此次日志处理了多个用户
    				accountLogModel.setToUserName("投资用户");
    			}else{
    				//从缓存中获取用户对象
    				User toUser = UserUtils.getUserById(toUserId);
    				accountLogModel.setToUserName(toUser.getUserName());
    			}
    		}
    	}
    }

    @Override
    public double todayEarnAmount(long userId) {
    	String today = DateUtil.dateStr2(DateUtil.getNow());
    	Double amount = accountLogMapper.earnAmount(userId, today);
    	return amount == null ? 0.0D : amount;
    }

    @Override
    public double earnAmount(long userId) {
    	// userId < 0， 则查询所有用户累计净收益
    	Double amount = accountLogMapper.earnAmount(userId, null);
        return amount == null ? 0.0D : amount;
    }

    @Override
    public double earnAmount() {
    	return earnAmount(-99);
    }

    @Override
    public double amount(String type, String month) {
    	Double amount = accountLogMapper.monthAmountByType(type, month);
    	return amount == null ? 0.0D : amount;
    }


    public List<AccountLogModel> findAccountLogByUserId(long userId, int count) {
        return accountLogMapper.findAccountLogByUserId(userId, count);
    }

	@Override
	public void addAccountLog(Account account, long toUserId, double amount) {
		
		// 增加资金变更log
		Map<String, Object> reasonMap = Global.getTransfer();
		String nid = (String) reasonMap.get(LogTplNid.LOG_TPL_KEY);

		AccountLog accountLog = new AccountLog();
		accountLog.setUserId(account.getUserId());
		accountLog.setType(nid);
		accountLog.setTotal(account.getTotal());
		accountLog.setMoney(amount);
		accountLog.setUseMoney(account.getUseMoney());
		accountLog.setNoUseMoney(accountLog.getNoUseMoney());
		accountLog.setCollection(account.getCollection());
		accountLog.setToUserId(toUserId);
		accountLog.setName(LogTemplateHelper.getLogTempName(LogTemplateType.ACCOUNT_LOG, nid));
		accountLog.setRemark(getLogRemark(nid));
		accountLog.setAddIp(Global.getIP());
		accountLog.setPaymentsType(LogTemplateHelper.getPaymentType(LogTemplateType.ACCOUNT_LOG, nid));
		accountLog.setAddTime(DateUtil.getNow());
		
		accountLogMapper.insert(accountLog);
		
	}

	@Override
	public PageDataList<AccountLogModel> list(AccountLogModel model, int pageNumber, int pageSize) {
		List<AccountLogModel> accountLogModelList;

		//使用分页代理器
		PageProxyBuilder<AccountLogMapper> proxy = PageProxyBuilder.newBuilder(AccountLogMapper.class);
		proxy.setPageParameter(pageNumber, pageSize);
		model.setStartDateAndEndDate();
		Date nowDate = DateUtil.getNow();
		Date rollDay;
		if (model.getTime() == 7) {
			rollDay=DateUtil.rollDay(nowDate, -7);
			model.setNowTime(nowDate);
			model.setRollDay(rollDay);
		}
		else if ((model.getTime() > 0) && (model.getTime() < 4)) {
			rollDay = DateUtil.rollMon(nowDate, -model.getTime());
			model.setNowTime(nowDate);
			model.setRollDay(rollDay);
       	}
		if(model.getStatus().equals("0")){
			model.setStatus("undefined");
		}

		accountLogModelList = proxy.createProxy().list(model);

		//获取分页参数
		PageParameter pageParameter = proxy.getPageParameter();

		PageDataList<AccountLogModel> pageDataList = new PageDataList<AccountLogModel>(pageParameter.convert2Page(), accountLogModelList);

		return pageDataList;
	}

	/**
	 * 获取根据模板生成备注信息
	 *
	 * @author Kaiju Zhao
	 * @param nid
	 */
	private String getLogRemark(String nid) {
		String template = LogTemplateHelper.getValue(LogTemplateType.ACCOUNT_LOG, nid);
		try {
			return FreemarkerUtil.renderTemplate(template, Global.getTransfer());
		} catch (Exception e) {
			logger.error("[资金日志 AccountLog] 添加资金日志Freemarker模版"+ template + "错误!", e);
		}
		return "";
	}

}
